// useLoading.js
import { ref } from 'vue'

// eslint-disable-next-line no-unused-vars
let timer = null
let startTime = Date.now()
let endTime = ''

export function useLoading() {
  const isLoading = ref(false)
  const isEmpty = ref(false)

  // 开始加载
  const startLoading = () => {
    clearTimeout(timer)
    isLoading.value = true
    isEmpty.value = false
  }

  // 结束加载
  const endLoading = (data) => {
    if (endTime - startTime > 500) {
      isLoading.value = false
      isEmpty.value = !data || (Array.isArray(data) && data.length === 0)
      return
    }
    timer = setTimeout(() => {
      isLoading.value = false
      isEmpty.value = !data || (Array.isArray(data) && data.length === 0)
    }, 1000)
  }

  // 加载数据（封装请求）
  const withLoading = async (promise) => {
    startTime = Date.now()
    startLoading()
    try {
      const data = await promise()
      endTime = Date.now()
      endLoading(data)
      return data
    } catch (error) {
      endTime = Date.now()
      endLoading(null)
      throw error
    }
  }

  return {
    isLoading,
    isEmpty,
    startLoading,
    endLoading,
    withLoading
  }
}
